#include <bits/stdc++.h>
using namespace std;

const int MOD = 1e9 + 7;
//  pow(a,b)
int qpow(int a, int b) {
  int res = 1;
  while (b) {
    if (b % 2 == 1)
      res = 1LL * res * a % MOD;
    a = 1LL * a * a % MOD;
    b >>= 1;
  }
  return res;
}

void work() {
  int n;
  cin >> n;
  vector<int> a(n + 1, 0);
  vector<int> amap(n + 1, 0); // 记下a数组每个数字的位置
  vector<int> b(n + 1, 0);

  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    amap[a[i]] = i;
  }

  for (int i = 1; i <= n; i++) {
    cin >> b[i];
  }

  int k = 0; // 连锁环的个数
  map<int, int> mp;
  mp.clear();

  for (int i = 1; i <= n; i++) {
    if (mp[i] == 1)
      continue;

    /*
    上下一样算不算环
    if (a[i] == b[i]) {
       mp[i] = 1;
       continue;
     } */
    // 寻找环
    int p = i;
    do {
      p = amap[b[p]];
      mp[p] = 1;
      // cout << ":" << p << endl;
    } while (p != i);
    k++;
  }
  cout << qpow(2, k) << endl;
}
int main() {
  int T;
  cin >> T;
  for (int i = 1; i <= T; i++) {
    work();
  }
  return 0;
}